/**
 * shenc
 * 2016/9/8.
 * 购物车页面js
 * 调用方式
 * new ListHandler(config);
 */

function ListHandler(config) {
    var This=this;
    var def={
        delUrl:'',
        url:'',
        payUrl:'',
        orderUrl:'',
        ajaxType:'post'
    };
    this.xhr=null;
    this.domData={cartGoods:[],_token:_token||''};
    this.eGoods=[];
    this.cGoods=[];
    this.config=$.extend({},def,config||{});
    this.wrap = $('.ui-cart-container');
    this.lists=this.wrap.find('.ui-cart-one');
    this._e={
        checkAll:function () {
            // 单选联动
            var that=$(this);
            var ckOne=that.closest('.ui-cart-one').find('.li-item').not('.ui-goods-disabled').find('.J-checkOne');
            ckOne.length&&ckOne.prop('checked',this.checked);

            This.ajaxData();
        },
        checkOne:function () {
            // 全选联动
            var that=$(this);
            var cartOne=that.closest('.ui-cart-one');
            var clAll=cartOne.find('.J-checkAll');
            var notChecked=cartOne.find('.li-item').not('.ui-goods-disabled').find('.J-checkOne').filter(function () {return !this.checked;});
            clAll.prop('checked',!notChecked.length);
            This.domData.current=that.closest('.li-item').attr('data-id');

            This.ajaxData();
        },
        numChange:function () {
            var that=$(this),checkbox=that.closest('.li-item').find('.J-checkOne');
            var isChecked=checkbox.prop('checked');

            // 1 判断是否选中   选中：ajax更新   未选择：无操作
            if(isChecked){
                This.ajaxData(function () {},that.closest('.li-item').attr('data-id'));
            }else{
                checkbox.triggerFastClick();
            }
        },
        deleteOne:function () {
            var that=$(this),isDisable=that.hasClass('ui-goods-disabled'),
                isChecked=that.closest('.li-item').find('.J-checkOne').prop('checked');

            var dia = $.dialog({
                title:'温馨提示',
                content:'确定要删除吗？',
                button:["确定","取消"]
            });
            dia.on("dialog:action",function(e){
                if(e.index==1) return false;
                if(isDisable||!isChecked){
                    delAnimate(that,$.noop);
                }else{
                    delAnimate(that,function () {
                        This.ajaxData();
                    });
                }
            });

            function delAnimate(delBtn,cb) {
                var callback=function (res) {
                    var ul=delBtn.closest('ul'),lis=ul.find('.li-item');
                    //3种状态  1：多个商品，只删除本商品  2：商品只有1个时，删除该分类  3：只有一类时 刷新页面
                    if(lis.length>1){
                        delBtn.closest('.li-item').fadeOut(500,function () {$(this).remove();});
                    }else{
                        if(This.wrap.find('.ui-cart-one').length==1){
                            var tpl='<section class="ui-cart-nodata">'
                                +'<i class="ui-icon-cart"></i>'
                                +'<small class="af-txt-muted">购物车里空空如也，赶紧去逛逛吧！</small>'
                                +'<p><a class="ui-btn ui-btn-sm" href="/">去逛逛</a></p>'
                                +'</section>';
                            This.wrap.append(tpl);
                        }
                        ul.closest('.ui-cart-one').fadeOut(500,function () {$(this).remove();});
                    }

                    typeof cb=='function'&&cb();
                };
                MyAjax(This.config.delUrl,'delete',{'goods_ids':[that.closest('.li-item').attr('data-id')]},callback);
            }
        },
        goToPay:function () {
            var that = $(this);
            var type=that.closest('.ui-cart-one').attr('data-type');
            if (that.hasClass('disabled') || that.prop('disabled')) return false;

            var data = This[type=='eShop'?'eGoods':'cGoods'];
            if (data.length == 0){
                topTip('请选择要购买的商品',{type:'warn'});
                return false;
            }

            MyAjax(This.config.payUrl,'post',{cartGoods:data,_token:_token||''},function(res){
                window.location.href = This.config.orderUrl;
            });
        }
    };
    this.ajaxData=function (callback,id) {
        var opts=this.config;

        This.getDOMData();//获取dom数据
        if(this.xhr){
            this.xhr.abort();
        }
        if(This.domData.cartGoods.length==0){
            var data={
                eshopGoods:{
                    pay_price:0,
                    shopGoods:[],
                    total_discount_price:"0.00",
                    total_number:0,
                    total_number_not:0,
                    total_price:"0.00",
                    total_tariff_price:"0.00"
                },
                cshopGoods:{
                    pay_price:0,
                    shopGoods:[],
                    total_discount_price:"0.00",
                    total_number:0,
                    total_number_not:0,
                    total_price:"0.00",
                    total_tariff_price:"0.00"
                },
                pay_price:0,
                total_discount_price:0,
                total_number:0,
                total_number_not:0,
                total_price:0,
                total_tariff_price:0
            };
            This.setDOMData({info:data});
            return false;
        }
        id=typeof id=='undefined'?'':id;
        id=id===''?This.domData.cartGoods[0].goods_id:id;

        this.xhr=$.ajax({
            url:opts.url+'/'+id,
            type:'post',
            dataType:'json',
            data:This.domData,
            success:function (res) {

                if(res.info){
                    //更新展示信息
                    This.setDOMData(res);
                    //回调方法
                    typeof callback ==='function' &&callback(res);
                }else if(res.status==0&&res.message){
                    //出错处理
                    Alert(res.message);
                    This.lists.find('.J-checkAll').prop('checked',false);
                    This.lists.find('.J-checkOne').prop('checked',false);
                }
            },
            error:function (error,errorType) {
                var msg='';
                if(errorType=='abort'){
                    return false;
                }
                if(errorType=='timeout'){
                    msg='请求超时！';
                }else{
                    msg=error.message||'操作失败'
                }
                topTip(msg,{type:'warn'});
            }
        });
    };
    this.getDOMData=function () {
        var cartGoods=[];
        var eGoods=[];
        var cGoods=[];
        var lis=This.wrap.find('.li-item').filter(function () {return !($(this).hasClass('.ui-goods-disabled')||!$(this).find('.J-checkOne').prop('checked'));});
        for(var i=0;i<lis.length;i++){
            var that=lis.eq(i),id=that.attr('data-id'),num=that.find('.ui-num-input').val();
            var curData={goods_id:id,buy_num:num};
            cartGoods.push(curData);
            if(that.closest('.ui-cart-one').attr('data-type')=='cShop'){
                cGoods.push(curData);
            }else{
                eGoods.push(curData);
            }
        }
        This.domData.cartGoods=cartGoods;
        This.eGoods=eGoods;
        This.cGoods=cGoods;
    };
    this.setDOMData=function (res) {
        var eShopGoods=res.info.eshopGoods;
        var cShopGoods=res.info.cshopGoods;
        var eShopCart=This.wrap.find('[data-type="eShop"]');
        var cShopCart=This.wrap.find('[data-type="cShop"]');

        eShopCart[0]&&renderDOM(eShopCart,eShopGoods);
        cShopCart[0]&&renderDOM(cShopCart,cShopGoods);

        //渲染DOM
        //设置总关税、价格、数量
        //设置E贸易商品关税、总价1000提示
        function renderDOM(dom,data) {
            var btn=dom.find('.J-toPay');
            var type=dom.attr('data-type');
            dom.find('.J-totalPrice').text((data.total_price*1).toFixed(2));
            dom.find('.J-tariff').text((data.total_tariff_price*1).toFixed(2));
            dom.find('.J-payPrice').text((data.pay_price*1).toFixed(2));
            dom.find('.J-totalNum').text(data.total_number);
            btn.toggleClass('disabled',!data.total_number).prop('disabled',!data.total_number);

            //e贸易限额提示
            if(type=='eShop'&&data.total_price>=1000&&data.total_number>1){
                dom.find('.J-PurchaseTip').show();
                btn.addClass('disabled').prop('disabled',!0);
            }else{
                dom.find('.J-PurchaseTip').hide();
                btn.removeClass('disabled').prop('disabled',!1);
            }
        }

    };
    this.init=function () {
        if(this.lists.length===0) return false;//无商品

        this.lists.find('.J-checkAll').prop('checked',false);
        this.lists.find('.J-checkOne').prop('checked',false);

        //获取数据
        this.getDOMData();

        this.lists.each(function () {
           var list=$(this),ckAll=list.find('.J-checkAll'),lis=list.find('.li-item').not('.ui-goods-disabled'),ckOne=lis.find('.J-checkOne'),
               numIpt=lis.find('.ui-num-input'),delBtn=list.find('.ui-icon-delete'),toPay=list.find('.J-toPay');
            var listId='cartOne_'+Date.now();

            list.attr('id',listId);

            //全选
            ckAll.on('click',function () {
               This._e.checkAll.call(this);
            });

            //单选
            ckOne.on('click',function () {
               This._e.checkOne.call(this);
            });

            //修改数量
            numIpt.on('change',function () {
               This._e.numChange.call(this);
            });

            //删除
            delBtn.on('click',function () {
                This._e.deleteOne.call(this);
            });

            //下单
            toPay.on('click',function () {
               This._e.goToPay.call(this);
            });
        });
    };

    return this.init();
}